package au.org.arcs.dss.client.tds.imos.datasource;

import java.io.*;
import javax.servlet.http.*;

import ucar.nc2.NetcdfFile;

import thredds.servlet.DatasetSource;

import au.org.arcs.dss.client.tds.utils.SystemUtils;
import au.org.arcs.dss.client.tds.adapter.TDSAdapter;
import au.org.arcs.dss.provider.ConfigManager;
import au.org.arcs.dss.provider.DataSetServiceDelegate;
import au.org.arcs.dss.provider.dataset.DataSet;

/**
 *
 * @author ming
 */
public class DataSetSourceIMOSImpl implements DatasetSource {
  private String pathKey;

  /**
   * This method determines which URL is matched. Thus, the NetcdfFile will be provided.
   * @param req
   * @return
   */
  public boolean isMine(HttpServletRequest req) {
    String path = req.getPathInfo();
    boolean startWith = false;

    /*for (String key : ConfigManager.getRootPaths().keySet()) {
      startWith = path.startsWith("/" + key);

      if (startWith) {
        setPathKey(key);
        break;
      }
    }*/

    return startWith;
  }

  public NetcdfFile getNetcdfFile(HttpServletRequest req, HttpServletResponse res) throws IOException {
    DataSetServiceDelegate dataSetServiceDelegate = new DataSetServiceDelegate();

    DataSet dataSet = dataSetServiceDelegate.getDataSet( ConfigManager.getRootPath(getPathKey()) + SystemUtils.getDataSetPath(req.getPathInfo(), "/"+getPathKey()));

    return TDSAdapter.getNetcdfFile(dataSet);
  }

  /**
   * @return the pathKey
   */
  public String getPathKey() {
    return pathKey;
  }

  /**
   * @param pathKey the pathKey to set
   */
  public void setPathKey(String pathKey) {
    this.pathKey = pathKey;
  }
}
